package com.lingkun.demo.config.shiro;


import com.alibaba.fastjson.JSON;
import com.lingkun.demo.contants.Constant;
import com.lingkun.demo.exception.BusinessException;
import com.lingkun.demo.exception.code.BaseResponseCode;
import com.lingkun.demo.utils.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class CustomAccessControlFilter  extends AccessControlFilter {



    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        /**
         * 如果是true就流转到下一个链式调用，
         * 否则返回到 onAccessDenied 方法处理
        */
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        /**
         * 如果是true就流转到下一个链式调用，
         * 不会返回到下一个链式调用
         */

        HttpServletRequest  request =  (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

            log.info("request接口地址...{}-->",request.getRequestURI());
            log.info("request接口请求方式...{}-->",request.getMethod());
            log.info("request接口请求方式...{}-->",request.getHeader(Constant.ACCESS_TOKEN));
          //截取请求头的信息
          String  accessToken    =  request.getHeader(Constant.ACCESS_TOKEN);
          System.out.println(accessToken);
        try {
          if(StringUtils.isEmpty(accessToken)){
              throw new BusinessException(BaseResponseCode.TOKEN_NOT_NULL);
          }
          //提交token值
          CustomUsernamePasswordToken customUsernamePasswordToken = new CustomUsernamePasswordToken(accessToken) ;
          getSubject(servletRequest,servletResponse).login(customUsernamePasswordToken);
          }catch (BusinessException e){
              e.printStackTrace();
              customRsponse(servletResponse,e.getCode(),e.getMsg());
              return false;
          }catch (AuthenticationException e){
              if(e.getCause() instanceof BusinessException){
                  BusinessException exception= (BusinessException) e.getCause();
                  customRsponse(servletResponse,exception.getCode(),exception.getMsg());
              }else {
         customRsponse(servletResponse,BaseResponseCode.TOKEN_ERROR.getCode(),BaseResponseCode.TOKEN_ERROR.getMsg());
              }
              return false;
          }catch (Exception e){
              e.printStackTrace();
        customRsponse(servletResponse,BaseResponseCode.SYSTEM_ERROR.getCode(),BaseResponseCode.SYSTEM_ERROR.getMsg());
              return false;
          }
        return true;
    }


    private void customRsponse(ServletResponse response,int code, String msg) {
        // 自定义异常的类，用户返回给客户端相应的JSON格式的信息
        try {
            DataResult result = DataResult.getResult(code, msg);
            response.setContentType("application/json; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            String userJson = JSON.toJSONString(result);
            OutputStream out = response.getOutputStream();
            out.write(userJson.getBytes("UTF-8"));
            out.flush();
        } catch (IOException e) {
            log.error("eror={}", e);
        }
    }



}
